package com.ttai.presenter.base;


import com.google.gson.JsonObject;
import com.ttai.model.net.ResponseInfo;
import com.ttai.presenter.api.ResponseInfoApi;
import com.ttai.untils.Constant;


import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public abstract class BasePresenter {

    public ResponseInfoApi responseInfoApi;
    public Retrofit retrofit;

    //网络请求
    public BasePresenter() {


        //1.初始化retrofit对象
        //2.指定了访问服务器工程的主机名
        if (responseInfoApi == null){
            retrofit = new Retrofit.Builder().
                    baseUrl(Constant.BASE_URL).
                    addConverterFactory(GsonConverterFactory.create()).
                    build();
        }
        //3.指定具体的网络请求实体对象
        //发送一个网络请求(完整的链接地址,请求方式(GET POST),请求过程中参数,请求的响应结果)
        responseInfoApi = retrofit.create(ResponseInfoApi.class);
    }
    public class CallBackAdapter implements Callback<ResponseInfo>{
        @Override
        public void onResponse(Call<ResponseInfo> call, Response<ResponseInfo> response) {

            //请求成功,获取服务器返回的所有的json串
            ResponseInfo body = response.body();
            if (body.getCode()==200){
                //请求成功
                    JsonObject json = body.getData();
                    //抽象的解析json方法,让子类对json做具体的解析过程
                    parseJson(json);
            }else{
                //请求失败
//                String errorMessage = getErrorInfo(body.getCode());
                String errorMessage = body.getInfo();
                onFailure(call,new RuntimeException(errorMessage));
            }
        }


        @Override
        public void onFailure(Call<ResponseInfo> call, Throwable t) {
            if (t instanceof RuntimeException){
                //请求失败
                String message = t.getMessage();
                showError(message);
            }
        }
    }

//    protected abstract String getErrorInfo(String code);
    protected abstract void showError(String message);
    protected abstract void parseJson(JsonObject json);

}

